import poplib, re
from ftplib import FTP
from time import time

# Login info for the gmail accounts
POPHOST = ""
POPUSER = ""
POPPASS = ""

FTPHOST = ""
FTPUSER = ""
FTPPASS = ""

# reg expressions for extracting header data
re_from        = re.compile( "^From: (.*)" )
re_to          = re.compile( "^To: (.*)" )
re_subject     = re.compile( "^Subject: (.*)" )
re_virusresult = re.compile( "^X-Virus-Scan-Result: (.*)" )

def showMessage( msgHdr ):
  out = ( msgHdr["msgnum"], msgHdr["From"], msgHdr["Subject"],
msgHdr["Virus"] )
  print "%3d. %-30.30s   %-24.24s %-24.24s" % out

def scanMailboxMsgs():
  "refresh window contents"
  global deleteCount

  try:
    # log in to mail box
    pop = poplib.POP3_SSL(POPHOST,995) # Google's Gmail servers require SSL over port 995
    pop.user(POPUSER)
    pop.pass_( POPPASS)
    connected = True
    print "appear to have logged in"

    # compile our email address regular expression
    ee = re.compile(r'[\w\-][\w\-\.]*@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')

    # retrieve msg headers
    msgCount, msgTotalSize = pop.stat()

    emptyHdr = {
      "From" : "",
      "To" : "",
      "Subject" : "",
      "Virus" : "none"
      }
    matchREs = [
      ( re_from, "From" ),
      ( re_to, "To" ),
      ( re_subject, "Subject" ),
      ( re_virusresult, "Virus" )
      ]

    # open social graph summary file
    sg_file = open('sg_sum.txt', 'a')

    count = 0
    # for each message, display header info
    for n in range( msgCount ):
      msgnum = n+1 # msg nums are 1-based, not 0-based

      # increment counter
      count = count + 1
      print str(count)
      # Retrieve message header
      response, headerLines, bytes = pop.top(msgnum, 0)

      hdr = emptyHdr.copy()
      hdr["msgnum"] = msgnum
      hdr["size"] = bytes
      for line in headerLines:
        #print p.match(line)
        if (line.count("From:")>0):
          print "RAW TO LINE: " + line
          emails = ee.findall(line)
          for email in emails:
            from_email_addy = email 
            print "Extracted e-mail: "+str(from_email_addy)
        if (line.count("To:") > 0):
          print "RAW FROM LINE: " + line
          emails = ee.findall(line)
          emaillist= ""
          for email in emails:
            to_email_addy = email
            if (to_email_addy != "onegraph.import@gmail.com"):
              emaillist = emaillist + ("," + to_email_addy)
            print "Extracted To Email Addy: " + str(to_email_addy) 
          if (len(emaillist)>0):
            sg_file.write(str(time())+"|"+str(from_email_addy)+emaillist+ "\n")
        for reExpr,hdrField in matchREs:
          match = reExpr.match( line )
          if match:
            hdr[ hdrField ] = match.group(1).strip('"')

      # delete the message that we just processed 
      #showMessage( hdr )
      pop.dele(msgnum)
      deleteCount += 1

  except poplib.error_proto, detail:
    print "POP3 error:", detail

  if connected :
    pop.quit()
  sg_file.close()

  # Now FTP the social graph data to a secure location so that an ESS instance can grab it
  ftp = FTP("hinchcliffeandco.com")
  ftp.login(FTPUSER, FTPPASS)
  ftp.cwd("rails/public")
  f = open('sg_sum.txt','rb')                 # file to send
  ftp.storbinary('STOR sg_sum.txt', f)         # Send the file 

  print "social data file sent"

# ============= main script ===============
print "running..."
deleteCount = 0
scanMailboxMsgs()
print "Deleted", deleteCount, "messages"

